package com.yskj.mwk.utils;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yskj.mwk.bean.Xcxconfig;
import com.yskj.mwk.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WxUtils {
    @Autowired
    private UserMapper userMapper;

    //获取access_token
    public String getAccessToken() {
        //先从数据获取access_token和有效时间
        Xcxconfig xcx = userMapper.getAccessToken();
        String accessToken = (String) xcx.getAccess_token();
        long updateTimestamp = (Long) xcx.getUpdateTimestamp();
        String appid = xcx.getAppid();
        String secret = xcx.getSecret();
        try {
            if (System.currentTimeMillis() - updateTimestamp > 1000 * 60 * 60 * 1.8) {
                String result=HttpClientUtils.sendGetRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(result);
                JsonNode nameNode = rootNode.get("access_token");
                accessToken=nameNode.asText();
                userMapper.updateAccessToken(accessToken,System.currentTimeMillis());
                return accessToken;
            } else {
                return accessToken;
            }
        }catch (Exception e){

            return accessToken;
        }
    }

    //获取用户openid
    public String getOpenid(String code) {
        //先从数据获取access_token和有效时间
        Xcxconfig xcx = userMapper.getAccessToken();
        String appid = xcx.getAppid();
        String secret = xcx.getSecret();
        try {
            String result=HttpClientUtils.sendGetRequest("https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + appid + "&secret=" + secret+"&js_code="+code);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(result);
            JsonNode openid_json = rootNode.get("openid");
            String openid=openid_json.asText();
            //先判断openid是否存在，不存在则新增
            int num=userMapper.checkOpenid(openid);
            if(num<1){
                int resultNum=userMapper.insertOpenidToUser(openid, DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
                if(resultNum>=1){
                    return openid;
                }else{
                    return null;
                }
            }else{
                return openid;
            }
        }catch (Exception e){
            return null;
        }
    }
}
